import React from 'react';
import PropTypes from 'prop-types';
import {Button, Form, Row, Col} from 'antd';
import {FORM_OPTIONS, FORM_ROW_OPTIONS} from '../constants';
import {PERMISSION} from './constants';
import {saleOrderStatus, saleOrderTransportType, saleOrderType, saleOrderSource} from '../Enum';
import TextInput from 'Shared/components/TextInput';
import WrappedSelect from '../common/WrappedSelect';
import DateRangePicker from 'Shared/components/DateRangePicker';
import TagSelect from 'Shared/components/TagSelect';
import DealerSelectPanel from '../common/DealerSelect/SelectEdit';
import SearchSelectPanel from '../common/DutyUnitSelect/SelectEdit';
import {hasPermissions} from './utils';
import Export from '../common/Export';
import {getMarketDepartment, getAreas, getMarketDepartmentSimple, getAreasSimple} from './api';
import {injectIntl, language} from './intl';
import routes from './routes';
const FormItem = Form.Item;

const saleOrderTypeList = saleOrderType.toList(language);
const saleOrderTransportTypList = saleOrderTransportType.toList(language);
const saleOrderStatusList = saleOrderStatus.toList(language);
const saleOrderSourceList = saleOrderSource.toList(language);
class QueryPanel extends React.PureComponent {
    handleFilterChange = (value, name) => {
        this.props.onConditionsChange(name, value);
    }
    handleFilterPressEnter = (value, name) => {
        this.props.onConditionsChange(name, value);
        this.props.querySearch();
    }
    onSelectDealer = data => {
        this.props.onConditionsChange('dealerId', data.id);
        this.props.onQueryDealerChange({
            id: data.id,
            code: data.code,
            name: data.name,
        });
    }
    onSelectArea = data => {
        this.props.onConditionsChange('country', data.chineseName);
        this.props.onQueryAreaChange({
            id: data.id,
            code: data.code,
            name: data.chineseName,
        });
    }
    onSelectMarke = data => {
        this.props.onConditionsChange('marketDepartmentId', data.id);
        this.props.onQueryMarkeChange({
            id: data.id,
            code: data.code,
            name: data.name,
        });
    }
    render() {
        const operations = [];
        const dealerInfo = this.props.conditions.dealerId ? {
            id: this.props.queryDealer.id,
            code: this.props.queryDealer.code,
            name: this.props.queryDealer.name
        } : null;
        const areaInfo = this.props.conditions.country ? {
            id: this.props.queryArea.id,
            chineseName: this.props.queryArea.name
        } : null;
        const countryCondition = {
            type: 2,
        };
        const markeInfo = this.props.conditions.marketDepartmentId ? {
            id: this.props.queryMarke.id,
            name: this.props.queryMarke.name
        } : null;
        if(hasPermissions(this.props.permissions, PERMISSION.add))
            operations.push(<Button key="add" type="primary" href={`#${routes.add.url()}`}>{this.props.intl.formatMessage({
                id: 'queryPanel.operation.add',
                defaultMessage: '新增'
            })}</Button>);
        return (
            <div>
                <Form className="form-standard">
                    <Row>
                        <Col {...FORM_OPTIONS.col}>
                            <FormItem
                                label={this.props.intl.formatMessage({
                                    id: 'queryPanel.form.dealer',
                                    defaultMessage: '总代'
                                })}
                                {...FORM_OPTIONS.item} >
                                <DealerSelectPanel
                                    value={dealerInfo}
                                    onSelect={this.onSelectDealer} />
                            </FormItem>
                        </Col>
                        {
                            this.props.initEnum.brands.length !== 1 &&
                        <Col {...FORM_OPTIONS.col}>
                            <FormItem
                                label={this.props.intl.formatMessage({
                                    id: 'queryPanel.form.brandId',
                                    defaultMessage: '品牌'
                                })}
                                {...FORM_OPTIONS.item}>
                                <WrappedSelect
                                    allowClear
                                    name="brandId"
                                    value={this.props.conditions.brandId}
                                    options={this.props.initEnum.brands}
                                    onChange={this.handleFilterChange} />
                            </FormItem>
                        </Col>
                        }
                        <Col {...FORM_OPTIONS.col}>
                            <FormItem
                                label={this.props.intl.formatMessage({
                                    id: 'queryPanel.form.marketDepartmentId',
                                    defaultMessage: '大区'
                                })}
                                {...FORM_OPTIONS.item}>
                                <SearchSelectPanel
                                    value={markeInfo}
                                    getDutyUnits={getMarketDepartment}
                                    getDutyUnitSimple={getMarketDepartmentSimple}
                                    titleName={this.props.intl.formatMessage({
                                        id: 'queryPanel.form.marketDepartmentId',
                                        defaultMessage: '大区'
                                    })}
                                    isLabelMap={false}
                                    onSelect={this.onSelectMarke} />
                            </FormItem>
                        </Col>
                        <Col {...FORM_OPTIONS.col}>
                            <FormItem
                                label={this.props.intl.formatMessage({
                                    id: 'queryPanel.form.country',
                                    defaultMessage: '国家'
                                })}
                                {...FORM_OPTIONS.item}>
                                <SearchSelectPanel
                                    value={areaInfo}
                                    conditions={countryCondition}
                                    isCountry={true}
                                    getDutyUnits={getAreas}
                                    getDutyUnitSimple={getAreasSimple}
                                    titleName={this.props.intl.formatMessage({
                                        id: 'queryPanel.form.country',
                                        defaultMessage: '国家'
                                    })}
                                    onSelect={this.onSelectArea} />
                            </FormItem>
                        </Col>
                        <Col {...FORM_OPTIONS.col}>
                            <FormItem
                                label={this.props.intl.formatMessage({
                                    id: 'queryPanel.form.code',
                                    defaultMessage: '订单编号'
                                })}
                                {...FORM_OPTIONS.item}>
                                <TextInput
                                    name="code"
                                    value={this.props.conditions.code}
                                    onPressEnter={this.handleFilterPressEnter}
                                    onBlur={this.handleFilterChange} />
                            </FormItem>
                        </Col>
                        <Col {...FORM_OPTIONS.col}>
                            <FormItem
                                label={this.props.intl.formatMessage({
                                    id: 'queryPanel.form.piCode',
                                    defaultMessage: '源单据编号'
                                })}
                                {...FORM_OPTIONS.item}>
                                <TextInput
                                    name="piCode"
                                    value={this.props.conditions.piCode}
                                    onPressEnter={this.handleFilterPressEnter}
                                    onBlur={this.handleFilterChange} />
                            </FormItem>
                        </Col>
                        <Col {...FORM_OPTIONS.col}>
                            <FormItem
                                label={this.props.intl.formatMessage({
                                    id: 'queryPanel.form.kDBomCode',
                                    defaultMessage: 'KDBOM号'
                                })}
                                {...FORM_OPTIONS.item}>
                                <TextInput
                                    name="kDBomCode"
                                    value={this.props.conditions.kDBomCode}
                                    onPressEnter={this.handleFilterPressEnter}
                                    onBlur={this.handleFilterChange} />
                            </FormItem>
                        </Col>
                        <Col {...FORM_OPTIONS.col}>
                            <FormItem
                                label={this.props.intl.formatMessage({
                                    id: 'queryPanel.form.orderType',
                                    defaultMessage: '订单类型'
                                })}
                                {...FORM_OPTIONS.item}>
                                <WrappedSelect
                                    allowClear
                                    name="orderType"
                                    value={this.props.conditions.orderType}
                                    options={saleOrderTypeList}
                                    onChange={this.handleFilterChange} />
                            </FormItem>
                        </Col>
                        <Col {...FORM_OPTIONS.col}>
                            <FormItem label={this.props.intl.formatMessage({
                                id: 'queryPanel.form.transportType',
                                defaultMessage: '运输方式'
                            })} {...FORM_OPTIONS.item}>
                                <WrappedSelect
                                    allowClear
                                    name="transportType"
                                    value={this.props.conditions.transportType}
                                    options={saleOrderTransportTypList.filter(d => d.value !== 2)}
                                    onChange={this.handleFilterChange} />
                            </FormItem>
                        </Col>
                        <Col {...FORM_OPTIONS.col}>
                            <FormItem
                                label={this.props.intl.formatMessage({
                                    id: 'queryPanel.form.batchNumber',
                                    defaultMessage: '批次号'
                                })}
                                {...FORM_OPTIONS.item}>
                                <TextInput
                                    name="batchNumber"
                                    value={this.props.conditions.batchNumber}
                                    onPressEnter={this.handleFilterPressEnter}
                                    onBlur={this.handleFilterChange} />
                            </FormItem>
                        </Col>
                        <Col {...FORM_OPTIONS.col}>
                            <FormItem
                                label={this.props.intl.formatMessage({
                                    id: 'queryPanel.form.dataSource',
                                    defaultMessage: '数据来源'
                                })}
                                {...FORM_OPTIONS.item}>
                                <WrappedSelect
                                    allowClear
                                    name="dataSource"
                                    value={this.props.conditions.dataSource}
                                    options={saleOrderSourceList}
                                    onChange={this.handleFilterChange}/>
                            </FormItem>
                        </Col>
                        <Col {...FORM_OPTIONS.col}>
                            <FormItem
                                label={this.props.intl.formatMessage({
                                    id: 'queryPanel.form.createTime',
                                    defaultMessage: '创建时间'
                                })}
                                {...FORM_OPTIONS.item}>
                                <DateRangePicker name="createTime" value={this.props.conditions.createTime}
                                    onChange={this.handleFilterChange} />
                            </FormItem>
                        </Col>
                    </Row>
                    <Row>
                        <Col>
                            <FormItem label={this.props.intl.formatMessage({
                                id: 'queryPanel.form.status',
                                defaultMessage: '状态'
                            })} {...FORM_ROW_OPTIONS.item}>
                                <TagSelect
                                    name="status"
                                    value={this.props.conditions.status}
                                    options={saleOrderStatusList}
                                    onChange={this.handleFilterChange} />
                            </FormItem>
                        </Col>
                    </Row>
                    <Row>
                        <Col span={6}>
                            <Button key="query" type="primary" onClick={this.props.querySearch} loading={this.props.loading}>
                                {this.props.intl.formatMessage({
                                    id: 'queryPanel.btn.query',
                                    defaultMessage: '查询'
                                })}
                            </Button>
                            <Button key="clear" onClick={this.props.onResetClick}>
                                {this.props.intl.formatMessage({
                                    id: 'queryPanel.btn.reset',
                                    defaultMessage: '重置'
                                })}
                            </Button>
                        </Col>
                        <Col span={18} className="col-align-right">
                            {hasPermissions(this.props.permissions, PERMISSION.export) &&
                            <Export key={PERMISSION.export} exportRequest={this.props.onClickExport} />}
                            {operations}
                        </Col>
                    </Row>
                </Form>
            </div>);
    }
}

QueryPanel.propTypes = {
    conditions: PropTypes.object.isRequired,
    initEnum: PropTypes.object.isRequired,
    loading: PropTypes.bool.isRequired,
    permissions: PropTypes.array.isRequired,
    querySearch: PropTypes.func.isRequired,
    onClickExport: PropTypes.func.isRequired,
    onConditionsChange: PropTypes.func.isRequired,
    onQueryDealerChange: PropTypes.func.isRequired,
    onResetClick: PropTypes.func.isRequired,
    intl: PropTypes.object,
    isDealerUser: PropTypes.bool,
    queryArea: PropTypes.object,
    queryDealer: PropTypes.object,
    queryMarke: PropTypes.object,
};

import {connect} from 'react-redux';
import {
    saveQueryCondition,
    resetQueryPanel,
    querySearch,
    exportData,
    saveQueryDealer,
    saveMarkeQuery,
    saveAreaQuery
} from './actions';
import selectorFactory from 'Shared/utils/immutableToJsSelectorFactory';
import {createSelector} from 'reselect';

const getInitData = createSelector(
    state => state.getIn(['page', 'domainData', 'initData']),
    init => {
        const initData = init.toJS();
        const brands = initData.brands ? initData.brands.map(item => ({
            text: `${'('}${item.code}${')'}${item.name}`,
            value: item.id
        })) : [];
        const marketDepartments = initData.marketDepartments ? initData.marketDepartments.map(item => ({
            text: `${'('}${item.code}${')'}${item.name}`,
            value: item.id
        })) : [];
        return {
            brands,
            marketDepartments
        };
    }
);

const getConditions = selectorFactory(['page', 'appState', 'queryCondition']);
const getQueryDealer = selectorFactory(['page', 'appState', 'queryDealer']);
const getQueryMarke = selectorFactory(['page', 'appState', 'queryMarke']);
const getQueryArea = selectorFactory(['page', 'appState', 'queryArea']);
const getPermissions = selectorFactory(['page', 'domainData', 'permission', 'data']);
const mapStateToProps = state => ({
    loading: state.getIn((['page', 'domainData', 'list', 'isFetching'])),
    isDealerUser: state.getIn((['page', 'domainData', 'initData', 'isDealerUser'])),
    initEnum: getInitData(state),
    conditions: getConditions(state),
    queryDealer: getQueryDealer(state),
    queryArea: getQueryArea(state),
    queryMarke: getQueryMarke(state),
    permissions: getPermissions(state)
});

const mapDispatchToProps = dispatch => ({
    onConditionsChange: (name, value) => dispatch(saveQueryCondition(name, value)),
    onQueryDealerChange: data => dispatch(saveQueryDealer(data)),
    onQueryMarkeChange: data => dispatch(saveMarkeQuery(data)),
    onQueryAreaChange: data => dispatch(saveAreaQuery(data)),
    querySearch: () => dispatch(querySearch()),
    onResetClick: () => dispatch(resetQueryPanel()),
    onClickExport: () => dispatch(exportData())
});
export default connect(mapStateToProps, mapDispatchToProps)(injectIntl(QueryPanel));
